#include "typedef.h"
#include "os_tick.h"
#include "work.h"
#include "switch_driver.h"
#include "switch_bsp.h"


enum
{
    SWITCH_STEP0,
    SWITCH_STEP1,
    SWITCH_STEP2,
    SWITCH_STEP3,
};


struct SWITCH_BSP_S
{
    SysTick_t  T;
    SysTick_t tick;
    u16 OnMs;
    u16 OffMs;
    u8 step;
    E_SWITCH index;
};

static struct SWITCH_BSP_S switch_bsp[SWITCH_MAX] = {\
    {.T = 0},
};


void switch_init(void)
{//初始化为off状态引脚，on为反之引脚
    switch_driver_gpio_init(SWITCH_F_DARK, SWITCH_RESET);
    switch_driver_gpio_init(SWITCH_F_LIGHT, SWITCH_SET);
    switch_driver_gpio_init(SWITCH_PUL_EN, SWITCH_SET);
    switch_driver_gpio_init(SWITCH_DIR_EN, SWITCH_RESET);
}

static void switch_work(unsigned int data)
{
    struct SWITCH_BSP_S *p = (struct SWITCH_BSP_S *)data;

    if (systick_get_difference_assign(&p->T, t1ms) == 0)
        return;

    switch (p->step)
    {
        case SWITCH_STEP0:
            switch_driver_set_pin_on(p->index);
            p->step = SWITCH_STEP1;
            p->tick = p->OnMs;
            break;
        case SWITCH_STEP1:
            if (p->tick)
                p->tick--;
            if (0 == p->tick)
            {
                p->step = SWITCH_STEP2;
                p->tick = p->OffMs;
                switch_driver_set_pin_off(p->index);
            }
            break;
        case SWITCH_STEP2:
            if (p->tick)
                p->tick--;
            if (0 == p->tick)
            {
                p->tick = p->OnMs;
                p->step = SWITCH_STEP1;
                switch_driver_set_pin_on(p->index);
            }
            break;
        default:
            work_del(switch_work, data);
            break;
    }
}

void switch_off(E_SWITCH index)
{
    if (index >= SWITCH_MAX)
        return;

    work_del(switch_work, (unsigned int)&switch_bsp[index]);
    switch_driver_set_pin_off(index);
}

void switch_on(E_SWITCH index)
{
    if (index >= SWITCH_MAX)
        return;

    work_del(switch_work, (unsigned int)&switch_bsp[index]);
    switch_driver_set_pin_on(index);
}

u8 switch_status(E_SWITCH index)
{
    return switch_driver_on_off(index);
}

void switch_pwm(u8 index, u16 OnMs, u16 OffMs)
{
    if (index >= SWITCH_MAX)
        return;

    switch_bsp[index].OnMs		= OnMs;
    switch_bsp[index].OffMs		= OffMs;
    switch_bsp[index].step		= SWITCH_STEP0;
    switch_bsp[index].index		= (E_SWITCH)index;
    work_add_tail(switch_work, (unsigned int)&switch_bsp[index]);
}




